/* $RCSFile: AddPage.aspx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/PageModules/Pages/AddPage.aspx.cs $
 * $log$
 * Revision 20 2010/08/09 10:51:21  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:43:57  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:26  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Text;
using System.Collections;
using System.Data.SqlClient;
using System.Security.Principal;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Globalization;

using AddonNice.Core;
using AddonNice.Configuration;
using AddonNice.Diagnostics;
using AddonNice.Security;
using AddonNice.Helpers;
using AddonNice.Settings;
using AddonNice.Settings.Cache;
using AddonNice.UI;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.PageModules.Pages
{
	public partial class AddPage : EditItemPage
	{
        int NewPageID       =   -1;
        PagesDB pagesDB		=   new PagesDB();
        
        #region Page_Load
		/// <summary>
		/// The Page_Load server event handler on this page is used
		/// to populate a Page's layout settings on the page
		/// </summary>
		private void Page_Load(object sender, EventArgs e)
		{
            // If first visit to the page, update all entries
			if (!Page.IsPostBack) 
			{
				msgError.Visible = false;
    			BindData();
			}
		}
		#endregion

		#region Events
		
        /// <summary>
		/// return to the previous page if present
		/// </summary>
		protected override void OnCancel(EventArgs e)
		{
			string returnPage = HttpUrlBuilder.BuildUrl(int.Parse(Request.QueryString[StStr.returnPageID]));
            Redirect(returnPage,true);
		}
		
		
		/// <summary>
		/// commit the page information from the form to the database.
		/// </summary>
        void AddPage_Update(object sender, AddonNice.UI.ADNPageEventArgs e)
        {
            if ( PageTraceSwitch.Sw.TraceVerbose )
			    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AddPage AddPage_Update Page.IsValid : {0}", Page.IsValid),PageTraceSwitch.Sw.Info);
            try
            {
                NewPageID           =   SavePageData();

                // Flush all Page navigation cache keys. Very important for recovery the changes
                // made in all languages and not get a error if user change the Page parent.
                CurrentCache.RemoveGlobalPagesCacheKey();
                CurrentCache.RemoveAll(StStr.PageNavigationSettings);
                CurrentCache.RemoveAll(StStr.AuthorizedPageStripDetail);

                //Jump to Page option
                if (cb_JumpToPage.Checked )
                {
                    portalSettings.SelectMenuItem(NewPageID);
                    // Redirect to New Form 
                    UrlReferrer     =   HttpUrlBuilder.BuildUrl(NewPageID);
                }
                else
                {
                    // Do NOT Redirect to New Form 
                    // I guess every .aspx page needs to have a module tied to it. 
                    // or you will get an error about edit access denied. 
                    // Redirect to module settings page
                    string strarg   =   string.Format("mID={0}&{1}={2}", ModuleID,StStr.selectedItem,NewPageID);
                    UrlReferrer     =   HttpUrlBuilder.BuildUrlWithCustomAttributes(PageID, strarg);
                }
            }
            catch(Exception ex)
            {
                if ( PageTraceSwitch.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]AddPage AddPage_Update ex : {0}", ex),PageTraceSwitch.Sw.Info);
                throw;
            }
		}
		#endregion

		#region Methods

        /// <summary>
		/// Trigger used by SettingTable when a control needs to be updated
        /// Origin from this call is in OnUpdate
		/// </summary>
        private void EditTable_UpdateControl(object sender, SettingsTableItemEventArgs e)
		{
            if ( PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AddPage EditTable_UpdateControl NewPageID: {0}, e.CurrentItem.EditControl.ID: {1}, e.CurrentItem.Value: [{2}]", NewPageID,e.CurrentItem.EditControl.ID, e.CurrentItem.Value),PageTraceSwitch.Sw.Info);
            if ( NewPageID != -1 )
                pagesDB.UpdatePageSettings(NewPageID, e.CurrentItem.EditControl.ID, e.CurrentItem.Value);
		}
		
        /// <summary>
		/// The SavePageData helper method is used to persist the
		/// current tab settings to the database.
		/// </summary>
		private int SavePageData() 
		{
			// Construct Authorized User Roles string
			string authorizedRoles      =   string.Empty;

			// Before storing in db we must translate special roles like admin and all users in langage independant roles
            StringBuilder sb            =   new StringBuilder();
            foreach (ListItem item in authRoles.Items)
            {
                if ( item.Selected )
                {
                    string str          =   item.Text;
                    if (str == CRMAllUsers)
                        str             =   DBAllUser;
                    sb.AppendFormat("{0};", str);
                }
            }
            authorizedRoles             =   sb.ToString();
            if ( PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AddPage SavePageData authorizedRoles : {0}", authorizedRoles),PageTraceSwitch.Sw.Info);

			// Add Page info in the database
            try
            {
                portalSettings.FlushSkinImageMenuCache();
   				// Get Parent Tab Id Convert only once used many times
				int parentTabID         =   int.Parse(pagesDropDownList.SelectedValue);
                NewPageID               =   pagesDB.AddPage(portalSettings.PortalID, parentTabID, PageName.Text,
                                                DDLPageImage.SelectedItem.Value.Trim(), 990000,3,0,0,0,0,0,authorizedRoles);
            }
            catch (Exception exp)
            {
                if ( PageTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]AddPage SavePageData ex : {0}", exp),PageTraceSwitch.Sw.Info);
                throw;
            }

			// Update custom settings in the database
			EditTable.UpdateControls();

            // Add the selected module to Page
            if ( PageTraceSwitch.Sw.TraceVerbose)
			    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AddPage SavePageData moduleType.SelectedValue is null: {0}.",moduleType.SelectedValue == null),PageTraceSwitch.Sw.Info);
            ModulesDB modDB			        =	new ModulesDB();
		    ModuleItem m				    =   new ModuleItem();
            if ( ( rblAddModule.SelectedValue == "Yes" ) && ( moduleType.SelectedValue != null ))
            {
			    try
			    {
			        // All new modules go to the end of the contentpane
			        string selectedModule	=   moduleType.SelectedValue;

                    if ( PageTraceSwitch.Sw.TraceVerbose)
			            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AddPage SavePageData SelectedModule: {0}.",selectedModule),PageTraceSwitch.Sw.Info);
        			
			        // This allows the user to pick what type of people can view the module being added.
			        // If Authorised Roles is selected from the dropdown then every role that has view permission for the
			        // Add Role module will be added to the view permissions of the module being added.
			        int moduleDefID			=   Convert.ToInt32(selectedModule);
				    m.Title					=   string.Format("{0}1",moduleType.Text.Trim());

				    m.ModuleDefID			=   moduleDefID;
				    m.Order					=   1;
				    // save to database
                    if ( PageTraceSwitch.Sw.TraceVerbose)
			            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AddPage SavePageData save to database newModuleTitle: {0}, moduleDefID: {1}.",
                            m.Title,moduleDefID),PageTraceSwitch.Sw.Info);
                    m.ID					=   modDB.AddModule(NewPageID, 
                                                    m.Order, 
                                                    0,
                                                    StStr.contentPane, 
                                                    m.Title, 
                                                    m.ModuleDefID, 
                                                    0, 
                                                    DBAllUser2, DBAllUser2, DBAllUser2, DBAllUser2, Config.InternalAdminRole, Config.InternalAdminRole, Config.InternalAdminRole, 
                                                    false, 
                                                    false);
			    }
			    catch(Exception ex)
			    {
                    if ( PageTraceSwitch.Sw.TraceError )
				        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]AddPage SavePageData Adding Selected Module ex :{0}", ex),PageTraceSwitch.Sw.Info);
                    throw;
			    }
                if ( PageTraceSwitch.Sw.TraceVerbose)
			            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AddPage SavePageData created ModuleID: {0}",m.ID),PageTraceSwitch.Sw.Info);
            }
            if ( rblAddModuleBuilder.SelectedValue == "Yes" )
            {
                string DBAdmin2         =   Config.InternalAdminRole+";";
                string DBAllUser2		=   Config.InternallAllUsersRole+";";

                try
                {
                    // The new module inherits security from current page current module (current ModuleID) 
                    // so who can edit the tab properties/content can edit the module properties/content (except view that remains =)
                    int AddModuleID     =   modDB.GetModuleDefinitionByGuid(portalSettings.PortalID,new Guid(StStr.AddModuleGuid));
                    if ( AddModuleID > 0 )
                        modDB.AddModule(NewPageID,2,0,StStr.rightPane,"Add Module",AddModuleID, 0,
                                                                DBAdmin2, DBAllUser2,
                                                                DBAdmin2, DBAdmin2,
                                                                DBAdmin2, DBAdmin2,
                                                                DBAdmin2, false, false);
                }
                catch (Exception ex)
                {
                    if ( PageTraceSwitch.Sw.TraceError )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]AddPage Exception inserting 'AddModule' module ex : {0}", ex),PageTraceSwitch.Sw.Info);
                    throw;
                }
		        portalSettings.ReloadPortal(true);
                portalSettings.ReloadMenus();
            }
			return NewPageID;
		}

		/// <summary>
		/// The BindData helper method is used to update the Page's
		/// layout panes with the current configuration information
		/// </summary>
		private void BindData() 
		{
            moduleType.SelectFirst  =   true;
            moduleType.DataBind();

            EditTable.DataBind();
			
            PageSettings wPage      =   portalSettings.ActivePageSettings;

			// Populate Page Names, etc.
            PageName.Text           =   LocalizeHelper.Localize("TAB_NAME", "New Page");
			string parentPgId	    =   Request.QueryString["parentpageid"];
            // if null default to WebPages
            if ( string.IsNullOrEmpty(parentPgId) )
                parentPgId          =   StStr.strPageWebID;
            pagesDropDownList.SelectedTreeViewValue   =   parentPgId;
            pagesDropDownList.DataBind();
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AddPage BindData after BindData pagesDropDownList.Text : [{0}].", pagesDropDownList.Text),PageTraceSwitch.Sw.Info);

            // Populate the DDLPageImage and select existing
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AddPage before GetImageMenu PageImage:[{0}]",wPage.PageImage),PageTraceSwitch.Sw.Info);
            Hashtable htb           =   portalSettings.GetImageMenu();
            DDLPageImage.DataSource =   htb;
            DDLPageImage.DataBind();
            if ( wPage.PageImage != string.Empty )
                    DDLPageImage.SelectedValue  =   wPage.PageImage;
            else    DDLPageImage.SelectedIndex =   0;


			// Populate checkbox list with all security roles for this portal
			// and "check" the ones already configured for this Page
			// Clear existing items in checkboxlist
			authRoles.Items.Clear();
			ListItem allItem        =   new ListItem();

            allItem.Text            =   LocalizeHelper.Localize("ALL_USERS", "All Users");

            if (wPage.AuthorizedRoles.LastIndexOf(allItem.Text) > -1) 
			{
				allItem.Selected    =   true;
			}
			authRoles.Items.Add(allItem);
            // get the CRM Roles
            string[] CrmRoles       =   PortalSecurity.GetCRMRoles();
            foreach (string cr in CrmRoles)
            {
                ListItem lItem      =   new ListItem(cr);
                if (wPage.AuthorizedRoles.LastIndexOf(cr) > -1)
                {
                    lItem.Selected  =   true;
                }
                authRoles.Items.Add(lItem);
            }
		}

        #endregion

		#region Std Overrides

		override protected void OnInit(EventArgs e)
		{
			InitializeComponent();
			base.OnInit(e);
		}

		private void InitializeComponent() 
		{    
			Load                            +=  new EventHandler(Page_Load);
            Update                          +=  new PageEventHandler(AddPage_Update);
            EditTable.UpdateControl         +=  new UpdateControlEventHandler(EditTable_UpdateControl);
            // install limitations for display pages from the PortalPagesManager calling Module 
            pagesDropDownList.IncludeAdmin  =   moduleSettingsDic[AStr.showAdmin].ToBool();
            pagesDropDownList.SkipList      =   moduleSettingsDic[AStr.skipList].Value;
		}


        protected override System.Web.UI.WebControls.PlaceHolder placeHolderForButtons
		{
			get
			{ return PlaceHolderButtons; }
			set { }
		}

        protected override System.Web.UI.WebControls.PlaceHolder placeHolderForButtons2
		{
			get
			{ return PlaceHolderButtons2; }
			set { }
		}
	    #endregion
	}
}
